package com.dayu.web.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.FileSystemResource;
import org.yaml.snakeyaml.Yaml;

import com.alibaba.fastjson.JSON;
import com.dayu.finecomm.pojo.DeviceConfig;
import com.dayu.web.param.DeviceParam;
import com.dayu.web.vo.Device;

/**
 * yaml工具类
 * 
 * @author Chenjiawei
 *
 *         2017年6月1日
 */
public class YamlUtil {

	private final static String file = "config.yaml";

	/**
	 * 该文件是否存在
	 * 
	 * @return
	 */
	public static boolean isExist() {
		File f = new File(file);

		return f.exists();

	}

	/**
	 * 写入yaml
	 * 
	 * @param object
	 */
	public synchronized static void setProper(Object object) {

		Yaml yaml = new Yaml();
		try {
			yaml.load(new FileInputStream(file));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		String s = yaml.dumpAsMap(object);
		Pattern p = Pattern.compile("- !!.+$", Pattern.MULTILINE);
		s = p.matcher(s).replaceAll(" -");

		FileWriter fw = null;
		try {
			fw = new FileWriter(file);
			fw.write(s);
			fw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fw != null) {
					fw.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 读取网关
	 * 
	 * @return
	 */
	public static List<DeviceParam> getDevices() {
		try {

			List<DeviceParam> list = new ArrayList<DeviceParam>();

			List<DeviceConfig> lds = getDeviceConfig();
			for (DeviceConfig config : lds) {

				DeviceParam param = new DeviceParam();
				param.srcName = config.name;
				param.enable = config.enabled;
				param.name = config.name;
				param.host = config.host;
				param.port = config.port;
				param.prefix = config.prefix;
				param.type = config.type;
				param.protocols = config.protocols;

				list.add(param);
			}

			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 读取网关
	 * 
	 * @return
	 */
	public synchronized static List<DeviceConfig> getDeviceConfig() {
		try {
			YamlMapFactoryBean yaml = new YamlMapFactoryBean();
			yaml.setResources(new FileSystemResource(file));
			@SuppressWarnings("unchecked")
			List<Object> finecomms = (List<Object>) yaml.getObject().get("finecomms");

			List<DeviceConfig> instances = new ArrayList<DeviceConfig>();
			if (finecomms != null) {

				for (Object o : finecomms) {

					DeviceConfig config = JSON.parseObject(JSON.toJSONString(o), Device.class);
					instances.add(config);
				}
			}

			return instances;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
